package fy.form.listen.manager;

import java.util.List;

import org.apache.commons.logging.LogFactory;

import fy.form.hr_plans.conf.Hr_PlansConf;
import fy.form.hr_plans.manager.PlansManager;
import fy.form.listen.bean.CommonFlowBean;
import fy.form.listen.dao.MyCommonFlowDao;
import fy.form.listen.log.LogWriter;
import fy.form.listen.operate.FormOperatorCreator;
import fy.form.listen.operate.IFormOperator;
import fy.form.listen.set.IFormSetting;
import fy.util.MyUtil;

/**
 * 事件监听管理
 *
 * @author Administrator
 *
 */
public class CommonFormHandlerManager {

    private static org.apache.commons.logging.Log log = LogFactory
            .getLog(CommonFormHandlerManager.class);

    /**
     * 处理表单监听到的数据
     *
     * @param summaryID
     * @param logFilePath
     * @param flowStatus
     */
    public static void operate(long summaryID, String logFilePath,
            short flowStatus) {
        // 获取流程模板编号和流程发起人
        CommonFlowBean bean = MyCommonFlowDao
                .getTempleteCodeBySummaryId(summaryID);
        if (bean.getTempleteCode() != null
                && !"".equals(bean.getTempleteCode())) {
            if (flowStatus == IFormSetting.FINISH_STATUS
                    && "my_import".equals(bean.getTempleteCode())) {
                // 导入异常表单数据
                log.info("导入异常表单数据");
                importFormInfo(logFilePath, bean.getUserID());
            } else if (flowStatus == IFormSetting.FINISH_STATUS
                    && "my_import_plans".equals(bean.getTempleteCode())) {
                // 导入异常个人发展计划数据
                log.info("导入个人发展计划表数据");
                importPlans();
            } else {
                // 正常表单事件监听后，获取表单操作实例
                IFormOperator fo = FormOperatorCreator.createOperator(
                        bean.getTempleteCode(), flowStatus);
                if (fo != null) {
                    boolean success = false;

                    log.info(new StringBuilder().append("监听表单《")
                            .append(fo.getFormName()).append("》，SummaryId为：")
                            .append(summaryID).append("，状态为:")
                            .append(flowStatus));
                    try {
                        fo.setFlowStatus(flowStatus);
                        fo.setTempleteCode(bean.getTempleteCode());
                        fo.operate(summaryID, bean.getUserID());
                        success = fo.isSuccess();
                    } catch (Exception e) {
                        String msg = new StringBuilder()
                                .append("获取SummaryId为：").append(summaryID)
                                .append("，表单名称：《").append(fo.getFormName())
                                .append("》的数据失败").toString();
                        log.error(msg, e);
                        e.printStackTrace();
                    }

                    if (!success) {
                        LogWriter.writeError(logFilePath, summaryID);
                        log.info("log文件地址"+logFilePath);
                        log.error("发生异常：并写入日志");
                    }
                    fo = null;
                }
            }
        }
    }

    /**
     * 导入个人发展计划,根据summaryID列表
     */
    private static void importPlans() {
        List<Long> summaryList = MyImport.getSummaryArray_Plans();
        for (int i = 0, size = summaryList.size(); i < size; i++) {
            PlansManager pm = new PlansManager();
            if (pm.isPersonalDevelopmentPlans(summaryList.get(i))) {
                pm.save(Hr_PlansConf.STATE_START, "发送表单");
                pm.save(Hr_PlansConf.STATE_PROCESS, "表单审批");
                pm.save(Hr_PlansConf.STATE_FINISH, "结束事件");
            }
        }
    }

    /**
     * 导入表单，根据summaryID列表
     */
    private static void importFormInfo(String logFilePath, long memberID) {

        List<Long> summaryList = MyImport.getSummaryArray();
        log.info("导入数据版本2");
        log.info("监听表单，需要导入的异常表单总数：" + summaryList.size() + "张");
        for (int i = 0, size = summaryList.size(); i < size; i++) {
            try {
                String operator = MyImport.getOperator();

                if (MyUtil.strIsNotNull(operator)) {
                    IFormOperator fo = null;
                    try {
                        fo = (IFormOperator) Class.forName(operator)
                                .newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("导入数据发生异常，无法创建实例", e);
                    }
                    if (fo != null) {
                        boolean success = false;

                        try {
                            String formName = fo.getFormName();
                            fo.setTempleteCode(MyCommonFlowDao
                                    .getTempleteCodeBySummaryId(
                                            summaryList.get(i))
                                    .getTempleteCode());
                            fo.setFlowStatus((short) 1);
                            fo.operate(summaryList.get(i), memberID);
                            success = fo.isSuccess();

                            log.info(new StringBuilder().append("监听表单《")
                                    .append(formName).append("》，SummaryId为：")
                                    .append(summaryList.get(i)).append("，状态为:")
                                    .append("已结束"));
                        } catch (Exception e) {
                            String msg = new StringBuilder()
                                    .append("获取SummaryId为：")
                                    .append(summaryList.get(i))
                                    .append("，数据导入失败").toString();
                            log.error(msg, e);
                            e.printStackTrace();
                        }

                        if (!success) {
                            LogWriter.writeError(logFilePath,
                                    summaryList.get(i));
                            // log.error("发生异常：并写入日志，路径：" + logFilePath);
                        }
                        fo = null;
                    }
                } else {
                    log.error("导入数据发生异常，无法读取到类");
                    System.out.println("导入数据发生异常，无法读取到类");
                }
            } catch (Exception e1) {
                log.error("导入发生异常", e1);
                e1.printStackTrace();
            }
        }
    }

}
